<?php

namespace app\service\audioVideo;

use \Exception;
use app\common\controller\Common;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Console\Console;
use AlibabaCloud\SDK\Rtc\V20180111\Rtc;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Rtc\V20180111\Models\DeleteChannelRequest;
use AlibabaCloud\SDK\Rtc\V20180111\Models\RemoveTerminalsRequest;
use AlibabaCloud\SDK\Rtc\V20180111\Models\DescribeChannelUsersRequest;
use AlibabaCloud\SDK\Rtc\V20180111\Models\DescribeUserInfoInChannelRequest;
use AlibabaCloud\SDK\Rtc\V20180111\Models\DescribeChannelParticipantsRequest;


class RtcChannel extends Common
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Rtc Client
     * @author tangfen
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/rtc
        $config->endpoint = "rtc.aliyuncs.com";
        return new Rtc($config);
    }


    /**删除频道
     * @param $channelId
     * @return bool
     * @author tangfen
     */
    public static function deleteChannel($channelId)
    {
        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));
//        $client = self::createClient('LTAI5tCyXowyCz2K59WhaftT', 'Uxf1u9wZYHbbpfdmXNOQ84Zk6yYCa8');
        $deleteChannelRequest = new DeleteChannelRequest([
            "appId" => config('aly_config.app_id'),
            "channelId" => $channelId
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->deleteChannelWithOptions($deleteChannelRequest, $runtime);
            $data = json_decode(Utils::toJSONString($resp), true);

            if (isset($data['body']['RequestId']) && !empty($data['body']['RequestId'])) {

//            return $data['body']['RequestId'];
                return 'true';
            } else {
                return false;
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
//            return $error->message;
            // 诊断地址
            return $error->message;
//            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }

    }

    /**
     * 将指定终端用户从频道踢出
     * @return mixed
     * @author tangfen
     * $terminalIds  [
     * "113d04044fe658e2",
     * "113d04044fe658e2"
     * ]
     *
     */
    public function RemoveTerminals($terminalIds, $channelId)
    {
        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));
        $removeTerminalsRequest = new RemoveTerminalsRequest([
            "terminalIds" => $terminalIds,
            "appId" => config('aly_config.app_id'),
            "channelId" => $channelId
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $resp = $client->removeTerminalsWithOptions($removeTerminalsRequest, $runtime);
            $data = json_decode(Utils::toJSONString($resp), true);

            var_dump($data);die;

            if ($data['statusCode'] == 200) {
                return 'true';
//                return $data['body'];
            }
            return $data;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
//            return $error->message;
            // 诊断地址
            return $error->message;
//            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }

    /**
     * Notes:查询 Channel（频道）实时在线用户列表
     * User: tangfen
     * Date: 2023/12/22
     * Time: 20:53
     */
    public function DescribeChannelUsers($channelId)
    {
        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));
        $describeChannelUsersRequest = new DescribeChannelUsersRequest([
            "channelId" => $channelId,
            "appId" => config('aly_config.app_id'),
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $resp = $client->describeChannelUsersWithOptions($describeChannelUsersRequest, $runtime);
            $data = json_decode(Utils::toJSONString($resp), true);

            if ($data['statusCode'] == 200) {
                return true;
//                return $data['body'];
            }
            return $data;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
            return $error->message;
            // 诊断地址
//            var_dump($error->data["Recommend"]);
//            Utils::assertAsString($error->message);
        }

    }

    /**
     * Notes:查询用户在频道中实时信息
     * User: tangfen
     * Date: 2023/12/22
     * Time: 21:18
     */
    public function DescribeUserInfoInChannel($channelId, $userId)
    {
        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));
        $describeUserInfoInChannelRequest = new DescribeUserInfoInChannelRequest([
            "appId" => config('aly_config.app_id'),
            "channelId" => $channelId,
            "userId" => $userId
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $resp = $client->describeUserInfoInChannelWithOptions($describeUserInfoInChannelRequest, $runtime);
            $data = json_decode(Utils::toJSONString($resp), true);

            if ($data['statusCode'] == 200) {
                return true;
//                return $data['body'];
            }
            return $data;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return $error->message;
        }
    }

    /**
     * Notes:查询频道在线用户列表，不包含详细信息
     * User: tangfen
     * Date: 2023/12/22
     * Time: 21:23
     */
    public function DescribeChannelParticipants($channelId)
    {

        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));

        $describeChannelParticipantsRequest = new DescribeChannelParticipantsRequest([
            "appId" => config('aly_config.app_id'),
            "channelId" => $channelId,
            "order" => "desc",//asc
            "pageNum" => 1,
            "pageSize" => 15
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $client->describeChannelParticipantsWithOptions($describeChannelParticipantsRequest, $runtime);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return $error->message;
//            // 错误 message
//            var_dump($error->message);
//            // 诊断地址
//            var_dump($error->data["Recommend"]);
//            Utils::assertAsString($error->message);
        }

    }


}

